package com.campus.help.controller.admin;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.campus.help.common.PageResult;
import com.campus.help.common.Result;
import com.campus.help.dto.SecondHandCategoryDTO;
import com.campus.help.entity.SecondhandType;
import com.campus.help.mapper.SecondhandTypeMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 二手商品类别管理控制器
 *
 * @author campus-help
 * @since 2025-10-17
 */
@Slf4j
@RestController
@RequestMapping("/admin/second-hand-categories")
public class AdminSecondHandCategoryController {

    @Autowired
    private SecondhandTypeMapper secondhandTypeMapper;

    /**
     * 测试接口
     */
    @GetMapping("/test")
    public Result<String> test() {
        return Result.success("二手商品类别管理接口正常工作");
    }

    /**
     * 分页查询二手商品类别列表
     */
    @GetMapping
    public Result<PageResult<SecondHandCategoryDTO>> getCategoryPage(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "20") Integer size,
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) Integer status) {
        
        try {
            log.info("查询二手商品类别列表，页码：{}，每页大小：{}，关键词：{}，状态：{}", page, size, keyword, status);
            
            // 构建查询条件
            LambdaQueryWrapper<SecondhandType> queryWrapper = new LambdaQueryWrapper<>();
            
            // 关键词搜索（类型名称或描述）
            if (keyword != null && !keyword.trim().isEmpty()) {
                queryWrapper.and(wrapper -> wrapper
                    .like(SecondhandType::getTypeName, keyword)
                    .or()
                    .like(SecondhandType::getDescription, keyword)
                );
            }
            
            // 状态筛选
            if (status != null) {
                queryWrapper.eq(SecondhandType::getStatus, status);
            }
            
            // 未删除的数据
            queryWrapper.eq(SecondhandType::getDeleted, 0);
            
            // 按排序字段排序，然后按创建时间倒序
            queryWrapper.orderByAsc(SecondhandType::getSortOrder)
                       .orderByDesc(SecondhandType::getCreateTime);
            
            // 分页查询
            Page<SecondhandType> pageObj = new Page<>(page, size);
            IPage<SecondhandType> result = secondhandTypeMapper.selectPage(pageObj, queryWrapper);
            
            // 转换为DTO
            List<SecondHandCategoryDTO> dtoList = result.getRecords().stream()
                    .map(SecondHandCategoryDTO::fromEntity)
                    .collect(Collectors.toList());
            
            PageResult<SecondHandCategoryDTO> pageResult = new PageResult<>(
                result.getCurrent(),
                result.getSize(),
                result.getTotal(),
                dtoList
            );
            
            return Result.success(pageResult);
        } catch (Exception e) {
            log.error("查询二手商品类别列表失败", e);
            return Result.error("查询失败: " + e.getMessage());
        }
    }

    /**
     * 获取类别选项（用于下拉选择）
     */
    @GetMapping("/options")
    public Result<List<SecondHandCategoryDTO>> getCategoryOptions() {
        try {
            log.info("获取二手商品类别选项");
            
            LambdaQueryWrapper<SecondhandType> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(SecondhandType::getStatus, 1)  // 只查询启用的
                       .eq(SecondhandType::getDeleted, 0)   // 未删除的
                       .orderByAsc(SecondhandType::getSortOrder)
                       .orderByDesc(SecondhandType::getCreateTime);
            
            List<SecondhandType> list = secondhandTypeMapper.selectList(queryWrapper);
            
            // 转换为DTO
            List<SecondHandCategoryDTO> dtoList = list.stream()
                    .map(SecondHandCategoryDTO::fromEntity)
                    .collect(Collectors.toList());
            
            return Result.success(dtoList);
        } catch (Exception e) {
            log.error("获取二手商品类别选项失败", e);
            return Result.error("获取失败: " + e.getMessage());
        }
    }

    /**
     * 根据ID查询类别详情
     */
    @GetMapping("/{id}")
    public Result<SecondhandType> getCategoryById(@PathVariable Long id) {
        try {
            log.info("查询二手商品类别详情，ID：{}", id);
            
            SecondhandType category = secondhandTypeMapper.selectById(id);
            if (category == null || category.getDeleted() == 1) {
                return Result.error("类别不存在");
            }
            
            return Result.success(category);
        } catch (Exception e) {
            log.error("查询二手商品类别详情失败，ID：{}", id, e);
            return Result.error("查询失败: " + e.getMessage());
        }
    }

    /**
     * 添加二手商品类别
     */
    @PostMapping
    public Result<String> addCategory(@RequestBody SecondHandCategoryDTO categoryDTO) {
        try {
            log.info("添加二手商品类别，类别名称：{}", categoryDTO.getCategoryName());
            
            // 参数校验
            if (categoryDTO.getCategoryName() == null || categoryDTO.getCategoryName().trim().isEmpty()) {
                return Result.error("类别名称不能为空");
            }
            
            if (categoryDTO.getDescription() == null || categoryDTO.getDescription().trim().isEmpty()) {
                return Result.error("类别描述不能为空");
            }
            
            // 转换为实体
            SecondhandType category = categoryDTO.toEntity();
            
            // 设置默认值
            if (category.getSortOrder() == null) {
                category.setSortOrder(0);
            }
            
            if (category.getStatus() == null) {
                category.setStatus(1);
            }
            
            // 插入数据
            int result = secondhandTypeMapper.insert(category);
            if (result > 0) {
                return Result.success("添加成功");
            } else {
                return Result.error("添加失败");
            }
        } catch (Exception e) {
            log.error("添加二手商品类别失败", e);
            return Result.error("添加失败: " + e.getMessage());
        }
    }

    /**
     * 更新二手商品类别
     */
    @PutMapping("/{id}")
    public Result<String> updateCategory(@PathVariable Long id, @RequestBody SecondHandCategoryDTO categoryDTO) {
        try {
            log.info("更新二手商品类别，ID：{}，类别名称：{}", id, categoryDTO.getCategoryName());
            
            // 检查是否存在
            SecondhandType existing = secondhandTypeMapper.selectById(id);
            if (existing == null || existing.getDeleted() == 1) {
                return Result.error("类别不存在");
            }
            
            // 参数校验
            if (categoryDTO.getCategoryName() == null || categoryDTO.getCategoryName().trim().isEmpty()) {
                return Result.error("类别名称不能为空");
            }
            
            if (categoryDTO.getDescription() == null || categoryDTO.getDescription().trim().isEmpty()) {
                return Result.error("类别描述不能为空");
            }
            
            // 转换为实体
            SecondhandType category = categoryDTO.toEntity();
            
            // 设置ID并更新
            category.setId(id);
            int result = secondhandTypeMapper.updateById(category);
            
            if (result > 0) {
                return Result.success("更新成功");
            } else {
                return Result.error("更新失败");
            }
        } catch (Exception e) {
            log.error("更新二手商品类别失败，ID：{}", id, e);
            return Result.error("更新失败: " + e.getMessage());
        }
    }

    /**
     * 删除二手商品类别（逻辑删除）
     */
    @DeleteMapping("/{id}")
    public Result<String> deleteCategory(@PathVariable Long id) {
        try {
            log.info("删除二手商品类别，ID：{}", id);
            
            // 检查是否存在
            SecondhandType category = secondhandTypeMapper.selectById(id);
            if (category == null || category.getDeleted() == 1) {
                return Result.error("类别不存在");
            }
            
            // TODO: 检查是否有商品使用此类别
            
            // 逻辑删除
            category.setDeleted(1);
            int result = secondhandTypeMapper.updateById(category);
            
            if (result > 0) {
                return Result.success("删除成功");
            } else {
                return Result.error("删除失败");
            }
        } catch (Exception e) {
            log.error("删除二手商品类别失败，ID：{}", id, e);
            return Result.error("删除失败: " + e.getMessage());
        }
    }

    /**
     * 切换类别状态
     */
    @PutMapping("/{id}/status")
    public Result<String> toggleStatus(@PathVariable Long id, @RequestBody Map<String, Integer> requestBody) {
        try {
            Integer status = requestBody.get("status");
            log.info("切换二手商品类别状态，ID：{}，状态：{}", id, status);
            
            // 检查是否存在
            SecondhandType category = secondhandTypeMapper.selectById(id);
            if (category == null || category.getDeleted() == 1) {
                return Result.error("类别不存在");
            }
            
            // 状态校验
            if (status == null || (status != 0 && status != 1)) {
                return Result.error("状态值无效");
            }
            
            // 更新状态
            category.setStatus(status);
            int result = secondhandTypeMapper.updateById(category);
            
            if (result > 0) {
                String statusText = status == 1 ? "启用" : "禁用";
                return Result.success(statusText + "成功");
            } else {
                return Result.error("操作失败");
            }
        } catch (Exception e) {
            log.error("切换二手商品类别状态失败，ID：{}", id, e);
            return Result.error("操作失败: " + e.getMessage());
        }
    }
}

